package com.zat.mes.andrmes.dofun.work

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.media.RingtoneManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Html
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.CheckBox
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat.startActivityForResult
import androidx.core.content.ContextCompat.startActivity
 import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.zat.mes.andrmes.R
import com.zat.mes.andrmes.base.BaseActivity
import com.zat.mes.andrmes.data.LoginResultBean
import com.zat.mes.andrmes.data.PackBean
import com.zat.mes.andrmes.data.PaiZaiBean
import com.zat.mes.andrmes.data.PaiZaiDetailBean
import com.zat.mes.andrmes.dofun.QrScanActivity
import com.zat.mes.andrmes.dofun.work.adapter.UpdatePackQtyDetailAdapter
import com.zat.mes.andrmes.dofun.work.vm.GetPackModel
import com.zat.mes.andrmes.dofun.work.vm.WorkRecordViewModel
import com.zat.mes.andrmes.global.CompanionCode
import com.zat.mes.andrmes.global.CompanionType
import com.zat.mes.andrmes.utils.ActivityUtils.finish
import com.zat.mes.andrmes.utils.PreferencesUtil
import com.zat.mes.andrmes.utils.ReadCardUtils
import com.zat.mes.andrmes.utils.SystemActivityUtil
import com.zat.mes.andrmes.utils.showToast
import kotlinx.android.synthetic.main.activity_bind_clothes.*
import kotlinx.android.synthetic.main.activity_update_pack_qty.*
import kotlinx.android.synthetic.main.layout_head_clock.*
import kotlinx.android.synthetic.main.layout_title.*
import org.json.JSONObject
import permissions.dispatcher.*

@RuntimePermissions
class BindClothesActivity : BaseActivity() {


    //U口读卡器,类似于外接键盘
    private var readCardUtils: ReadCardUtils? = null
    private var recordViewModel: WorkRecordViewModel? = null
    private var thisPackBean: PackBean? = null
    private var getPackModel: GetPackModel? = null
    var paiZaiBean:PaiZaiBean?=null

       override fun init() {
        initView()
        initData()
    }

    private fun initData() {

        recordViewModel = ViewModelProvider(this).get(WorkRecordViewModel::class.java)
        recordViewModel?.getPackData()?.observe(this, androidx.lifecycle.Observer {
            closeLoading()
            if (it == null) {
                showToast(getString(R.string.text_not_find_pack))
            } else {
                thisPackBean = it
                tvPackStyleNo.text = "当前款号："+thisPackBean?.packNO
                tvPackStyleName.text = "当前款名："+thisPackBean?.productName
                tvPackColor.text = "当前颜色："+thisPackBean?.color
                tvPackSize.text = "当前尺码："+thisPackBean?.size
                tvPackNo.text = "当前包号："+thisPackBean?.packNO
                val loginResultBean = Gson().fromJson(
                    PreferencesUtil.getString(CompanionType.LOGIN_RESULT),
                    LoginResultBean::class.java
                )
                tvEmpname.text=loginResultBean.empname



            }

        })
        recordViewModel?.getBindClothes()?.observe(this, Observer {
            closeLoading()
            showToast(it)
        })
        readCardUtils = ReadCardUtils()
        initCardReader()

        getPackModel = ViewModelProvider(this).get(GetPackModel::class.java)
        getPackModel?.getPaiZaiData()?.observe(this, Observer {
            closeLoading()
            if (it != null) {
                textData(it)
            }
        })

    }

    private fun textData(it: PaiZaiBean?) {
        paiZaiBean=it
        tvPackStyleNo.text = "当前计划号："+it?.orderNo
        tvPackStyleName.text = "当前款名："+it?.styleNo
        tvPackColor.text = "当前颜色："+it?.color
        tvPackSize.text = "当前尺码："+it?.size
        tvPackNo.text = "当前包码："+it?.code
        val loginResultBean = Gson().fromJson(
            PreferencesUtil.getString(CompanionType.LOGIN_RESULT),
            LoginResultBean::class.java
        )
        tvEmpname.text="操作者："+loginResultBean.empname
        tvDetailsList.text= Html.fromHtml("<u>"+"物料明细"+"</u>")
        tvDetailsList.setOnClickListener {
            var view=
                LayoutInflater.from(this).inflate(R.layout.layout_update_pack_qty_detail_list,null)
            val dataRV=view.findViewById<RecyclerView>(R.id.detailsListRV)
            dataRV.layoutManager = LinearLayoutManager(this)
            val updatePackQtyDetailAdapter = UpdatePackQtyDetailAdapter(R.layout.item_update_pack_qty_detail)
            dataRV.adapter = updatePackQtyDetailAdapter
            view.findViewById<CheckBox>(R.id.checkbox).visibility=View.GONE
            updatePackQtyDetailAdapter.setNewInstance(paiZaiBean?.detailList as MutableList<PaiZaiDetailBean>)
            val dialog= AlertDialog.Builder(this).setTitle("物料明细").setView(view).create()
            dialog.show()
        }
    }

    /**
     * 初始化刷卡器
     */
    private fun initCardReader() {

        readCardUtils?.setReadSuccessListener(ReadCardUtils.OnReadSuccessListener() {
            Log.e("zhangyucode", "barcode: " + it);
            if (it.length == 8 || it.length == 10) {
                //叫唤
                val notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
                val r = RingtoneManager.getRingtone(applicationContext, notification)
                r.play()
//                val soundPool = SoundPool(2, AudioManager.STREAM_MUSIC, 0)
//                soundPool.load(this,R.raw.ondo,1)
//                soundPool.play(1,1f, 1f, 0, 0, 1f);
                showLoading()
                recordViewModel?.loadPackDataByRFRD(it)
            }
        });
    }


    private fun initView() {
        setContentView(R.layout.activity_bind_clothes)
        tVtitle.text = "衣服绑码"
        rlReturnTitle.visibility = View.VISIBLE
        rlReturnTitle.setOnClickListener { finish() }

        btnBindPack.setOnClickListener {
            showCameraWithPermissionCheck()
        }
        btnBindClothes.setOnClickListener {
            if(paiZaiBean==null){
                showToast("请先扫包")
                return@setOnClickListener
            }
            showCameraWithPermissionCheck()
        }
        btnBindWork.setOnClickListener {
            startActivity(
                Intent(
                    this,
                    DayWorkScanActivity::class.java
                )
            )
        }



    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        val qrCode = data?.getStringExtra(CompanionType.INTENT_EXTRA_QRCODE)
        if (resultCode == Activity.RESULT_OK) {
            //根据二维码查包
            showLoading()
            if (qrCode!=null){
                if (qrCode?.contains("qr:clothes")){
                    //衣服码
                    var json = JSONObject()
                   // json.put("packId",paiZaiBean?.packId)
                    json.put("packId",paiZaiBean?.id)
                    json.put("qRcode",qrCode)
                    recordViewModel?.bindClothes(json.toString())
                }else{
//                    recordViewModel?.loadPackData(qrCode)
                    getPackModel?.paiZaiInfo(qrCode!!)

                }
            }

        }
    }

    @NeedsPermission(Manifest.permission.CAMERA)
    fun showCamera() {
        try {
            startActivityForResult(
                Intent(this, QrScanActivity::class.java),
                CompanionCode.REQUESTCODE
            )
        } catch (e: Exception) {
            Log.e("activity", e.toString())
        }
    }

    @OnShowRationale(Manifest.permission.CAMERA)
    fun showRationaleForCamera(request: PermissionRequest) {
        request.proceed();
        Log.e("permission", "OnShowRationale")
    }

    @OnPermissionDenied(Manifest.permission.CAMERA)
    fun onCameraDenied() {
        showCameraWithPermissionCheck()
    }

    @OnNeverAskAgain(Manifest.permission.CAMERA)
    fun onCameraNeverAskAgain() {
//        showToast("请到设置打开相机权限")
        SystemActivityUtil.getAppDetailSettingIntent(this)
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        onRequestPermissionsResult(requestCode, grantResults)

    }
}
